package com.hnrd.crud.shiro;

import java.util.List;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hnrd.crud.mapper.PermissionMapper;
import com.hnrd.crud.mapper.TUserMapper;
import com.hnrd.crud.pojo.TUser;
@Component
public class MyRealm extends AuthorizingRealm{
	@Autowired
	private TUserMapper tUserMapper;
	@Autowired
	private PermissionMapper permissionMapper;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {//授权
		System.out.println("为当前用户授权");
		String username=(String) principals.getPrimaryPrincipal();
		List<String> permissions=permissionMapper.selectPermissonsByUserName(username);
		for (String string : permissions) {
			System.out.println("当前用户权限："+string);
		}	
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addStringPermissions(permissions);//授权给当前用户
		return simpleAuthorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//验证
		
		String username=(String) token.getPrincipal();
		TUser user= tUserMapper.selectByUsername(username);
		if (user==null) {
			throw new AuthenticationException();
		}
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getName(),user.getPassword(),"myRealm");
		simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("lhm"));//盐值，随机字符串，必须根据用户注册时所加的盐值一致
		return simpleAuthenticationInfo;
	}
	
}
